/* eslint-disable import/no-dynamic-require */
const path = require('path');
const fs = require('fs-extra');
const webpack = require('webpack');
const rimraf = require('rimraf');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');

const config = require(`../config/webpack.${process.argv[2]}.conf.js`);

async function build() {
  const publicFolder = path.join(__dirname, '../public');
  const buildFolder = path.join(__dirname, '../build');

  await new Promise((rs) => {
    rimraf(buildFolder, (err) => {
      if (err) {
        console.error(err);
        process.exit(1);
      }
      rs();
    });
  });

  fs.mkdirSync(buildFolder);

  await new Promise((rs) => {
    fs.copy(
      publicFolder,
      buildFolder,
      (err) => {
        if (err) {
          console.error(err);
          process.exit(1);
        }
        rs();
      },
    );
  });

  const compiler = webpack(config);
  compiler.apply(new ProgressPlugin());
  compiler.run((err, stats) => {
    if (err) {
      console.error(err.stack || err);
      if (err.details) {
        console.error(err.details);
      }
      process.exit(1);
    }

    const info = stats.toJson();

    if (stats.hasErrors()) {
      info.errors.forEach((e) => {
        console.log(e);
      });
      process.exit(1);
    }

    if (stats.hasWarnings()) {
      info.warnings.forEach((e) => {
        console.log(e);
      });
      // process.exit(1);
    }
  });
}

build();
